import byteBuf from "./decode.js"
const SerialPort = window.require("serialport")

const serialPortOption = {
  autoOpen: true,
  baudRate: 9600,
  stopBits: 1,
  dataBits: 8,
  parity: "none",
}

class SerialPortUtil {
  constructor() {}
  open() {
    SerialPort.list().then(
      (ports) => ports.forEach((port) => console.log("port", port)),
      (error) => console.error('serialPort list error = ',error)
    )
    if (!this.port) {
      // 打开 COM2 串口
      this.port = new SerialPort("COM2", serialPortOption, (err) => {})
      // 监听串口 data 事件
      this.port.on("data", function (data) {
        console.log("receive data=", data)
        byteBuf.decode(data)
      })
    }
  }

  send(msg) {
    if (this.port) {
      this.port.write(msg, function (err) {
        if (err) {
          return console.log("Error on write: ", err.message)
        }
        console.log("message written")
      })
    }
  }
}

export default new SerialPortUtil()
